package com.yuedou.api.service.platfom.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yuedou.api.dao.platform.WxTemplateMapper;
import com.yuedou.api.entity.platform.Parameter;
import com.yuedou.api.entity.product.Product;
import com.yuedou.api.entity.product.ProductOrder;
import com.yuedou.api.entity.wxmsg.*;
import com.yuedou.api.entity.wxuser.User;
import com.yuedou.api.entity.wxuser.UserMp;
import com.yuedou.api.service.base.impl.BaseServiceImpl;
import com.yuedou.api.service.platfom.ParameterService;
import com.yuedou.api.service.platfom.WxTemplateService;
import com.yuedou.api.service.product.ProductService;
import com.yuedou.api.service.wxuser.UserMpService;
import com.yuedou.api.util.DateUtil;
import com.yuedou.api.util.MathUtil;
import com.yuedou.api.util.WxMessage;
import com.vdurmont.emoji.EmojiParser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;


@Service
public class WxTemplateServiceImpl extends BaseServiceImpl<WxTemplateMapper, WxTemplate> implements WxTemplateService {

    @Resource
    private UserMpService userMpService;
    @Resource
    private WxTemplateService wxTemplateService;
    @Resource
    protected RedisTemplate<String, Object> redisTemplate;
    @Resource
    private ParameterService parameterService;
    @Resource
    private ProductService productService;

    @Value("${web.appid}")
    private String appid;
    @Value("${web.secret}")
    private String secret;

    @Value("${web.appidMp}")
    private String appidMp;
    @Value("${web.secretMp}")
    private String secretMp;

    @Override
    public int sendWxMsgRefundProduct(User user, ProductOrder order, Integer template_type) {
        try{
            if(order != null){
                String access_token = wxTemplateService.getAccessToken(0);
                //给用户发送支付成功消息
                WxMsgTemplate template = getTemplateToUserByRefund(user,order,template_type);
                String param = JSONUtil.parseObj(template).toString();
                JSONObject jsonObject = WxMessage.sendMsg(access_token,param);
                System.out.println("公众号推送消息 - 用户端响应信息:" + jsonObject.toString());
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage(), e);
            System.out.println("发送失败" + e.getMessage());
        }
        return 1;
    }

    /**
     *  发送推送消息到 商家管理员微信上
     * @param user
     * @param order
     * @param template_type
     * @return
     */
    private WxMsgTemplate getTemplateToUserByRefund(User user, ProductOrder order, Integer template_type){
        WxMsgTemplate template = new WxMsgTemplate();
        WxTemplate wxTemplate = wxTemplateService.selectByUniqueColumn("template_type",template_type);
        QueryWrapper<UserMp> qw = new QueryWrapper<>();
        qw.eq("platform", user.getPlatform());
        qw.eq("union_id",user.getUnionId());
        qw.last("limit 1");
        UserMp userMp = userMpService.getOne(qw);
        if(userMp != null){
            template.setTouser(userMp.getOpenId());
            template.setTemplate_id(wxTemplate.getTemplateId());
            template.setUrl("");

            Map<String,Object> miniprogram = new HashMap<>();
            miniprogram.put("appid",appid);
            miniprogram.put("pagepath","pages/order/productList/index?index=0");
            template.setMiniprogram(miniprogram);

            Map<String, MsgTempData> m = new HashMap<>();
//            {{first.DATA}}
//            订单号：{{keyword1.DATA}}
//            商品：{{keyword2.DATA}}
//            退款金额：{{keyword3.DATA}}
//            客户名称：{{keyword4.DATA}}
//            退款原因：{{keyword5.DATA}}
//            {{remark.DATA}}
            MsgTempData first = new MsgTempData();
            first.setColor(wxTemplate.getFontColor());
            first.setValue("尊敬的用户您好，您的订单已退款完成！");
            m.put("first",first);

            //订单号
            MsgTempData keyword1 = new MsgTempData();
            keyword1.setColor(wxTemplate.getFontColor());
            keyword1.setValue(order.getOrderNo());
            m.put("keyword1",keyword1);

            //商品
            MsgTempData keyword2 = new MsgTempData();
            keyword2.setColor(wxTemplate.getFontColor());
            Product product = productService.getProductByOrderId(order.getId());
            if(product!=null){
                keyword2.setValue(product.getStoreName());
            }else{
                keyword2.setValue("");
            }
            m.put("keyword2",keyword2);


            //退款金额
            MsgTempData keyword3 = new MsgTempData();
            keyword3.setColor(wxTemplate.getFontColor());
            keyword3.setValue(MathUtil.getDoubleUp(order.getRefundPrice().doubleValue())+"");
            m.put("keyword3",keyword3);

            //客户名称
            MsgTempData keyword4 = new MsgTempData();
            keyword4.setColor(wxTemplate.getFontColor());
            keyword4.setValue(EmojiParser.parseToUnicode(user.getNickName()));
            m.put("keyword4",keyword4);


            //退款原因
            MsgTempData keyword5 = new MsgTempData();
            keyword5.setColor(wxTemplate.getFontColor());
            keyword5.setValue(StrUtil.isNotEmpty(order.getRefundReasonWapExplain())? order.getRefundReasonWapExplain() : "平台退款");
            m.put("keyword5",keyword4);

            //备注信息
            MsgTempData remark = new MsgTempData();
            remark.setColor(wxTemplate.getFontColor());
            remark.setValue("感谢您的使用,退款金额以到账为准");
            m.put("remark",remark);

            template.setData(m);
        }
        return template;
    }

    @Override
    @Transactional
    public String getAccessToken(int type) {
        String access_token = "";
        try{
            Parameter parameter = parameterService.findById(1);
            if(type == 0){//公众号
                access_token = parameter.getAccessTokenMp();
                if(new Date().getTime() > parameter.getAcMpLastTime().getTime()){
                    access_token = WxMessage.getACCESSTOKEN(appidMp,secretMp);
                    parameter.setAccessTokenMp(access_token);
                    //记录2小时之后的时间
                    parameter.setAcMpLastTime(DateUtil.getAfterSecondsByOld(new Date(),7000));
                    parameterService.updateById(parameter);
                }
            }else if(type == 1){//跃豆小程序
                access_token = parameter.getAccessToken();
                if(new Date().getTime() > parameter.getAcLastTime().getTime()) {
                    access_token = WxMessage.getACCESSTOKEN(appid, secret);
                    parameter.setAccessToken(access_token);
                    parameter.setAcLastTime(DateUtil.getAfterSecondsByOld(new Date(),7000));
                    parameterService.updateById(parameter);
                }
            }
            parameterService.resetParameter(1);
        }catch (Exception e){
            e.printStackTrace();
        }
        return access_token;
    }

}
